package com.cts.tmall.app.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cts.tmall.biz.service.BaseService;
import com.google.common.collect.ImmutableMap;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public class BaseController<T> {
    @Autowired
    private BaseService<T> service;

    @PostMapping
    public T save(@RequestBody @Validated(Insert.class) T entity) {
        return service.save(entity);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Serializable id) {
        service.deleteById(id);
    }

    @DeleteMapping
    public void deleteByIds(@RequestBody List<Serializable> ids) {
        service.deleteByIds(ids);
    }

    @PutMapping
    public T updateById(@RequestBody @Validated(Update.class) T entity) {
        return service.updateById(entity);
    }

    @GetMapping("/{id}")
    public T queryById(@PathVariable("id") Serializable id) {
        return service.queryById(id);
    }

    @GetMapping("/page")
    public Map queryPage(@RequestParam(name = "pageNumb", required = false, defaultValue = "1") Long pageNumb,
                         @RequestParam(name = "pageSize", required = false, defaultValue = "10") Long pageSize,
                         @Validated(Select.class) T entity) {
        Page<T> page = service.queryPage(entity, pageNumb, pageSize);
        return ImmutableMap.<String, Object>builder()
                .put("pageNumb", pageNumb)
                .put("pageSize", pageSize)
                .put("total", page.getTotal())
                .put("data", page.getRecords())
                .build();
    }

    @GetMapping
    public List<T> queryList(@Validated(Select.class) T entity) {
        return service.queryList(entity);
    }
}
